﻿#include "AudioOutputThread.h"
#include <QDebug>
#include <QThread>
#include <QAbstractEventDispatcher>
#include <QEventLoop>

AudioOutputThread::AudioOutputThread(const QAudioFormat &format, QObject *parent):
    m_format(format),
    m_buffer(nullptr)
{

}

AudioOutputThread::~AudioOutputThread()
{
    m_output->stop();
    m_output->deleteLater();
    qDebug() << "AudioOutputThread delete";
}

void AudioOutputThread::setBuffer(QIODevice *buffer)
{
    m_buffer = buffer;
}

void AudioOutputThread::run()
{
    if (!m_buffer)
        return ;

    /* 这里有个坑，如果QAudioOutput在外部创建，读取数据接口会在主线程中运行（可能是因为在实例化时，内部的信号槽和所在的线程有什么联系 */
    m_output = new QAudioOutput(m_format,this);

    //    m_output->setVolume(0.1);

    qDebug() << "run thread" << QThread::currentThreadId();

        connect(m_output,&QAudioOutput::stateChanged,[this](QAudio::State state){
            switch (state) {
            case QAudio::IdleState:
                qDebug() << "output idle" << QThread::currentThreadId();
                m_output->stop();/* 这里必须调用此，否则系统 */
                break;
            case QAudio::ActiveState:
                qDebug() << "output active"<< QThread::currentThreadId();
                break;

            case QAudio::SuspendedState:
                qDebug() << "output suspend"<< QThread::currentThreadId();
                break;
            case QAudio::StoppedState:
                qDebug() << "output stop"<< QThread::currentThreadId();
                break;
            default:
                break;
            }
        });

    m_output->start(m_buffer);
}

void AudioOutputThread::stop()
{
    qDebug() << "audio stop";
    m_output->stop();
}

void AudioOutputThread::pause(bool pause)
{
    if (pause) {
        m_output->start();
    } else {
        m_output->stop();
    }
}
